import 'package:shared_preferences/shared_preferences.dart';

/// 本地缓存
class StorageManager {
  factory StorageManager() => _getInstance();
  static StorageManager get instance => _getInstance();

  static StorageManager? _instance;
  static StorageManager _getInstance() {
    _instance ??= StorageManager._internal();
    return _instance!;
  }

  StorageManager._internal() {
    _prefFuture = _init();
  }

  late final Future<SharedPreferences> _prefFuture;
  late final SharedPreferences _pref;

  Future<SharedPreferences> _init() async {
    return await SharedPreferences.getInstance();
  }

  Future<void> preInit() async {
    _pref = await SharedPreferences.getInstance();
  }

  /// 通过泛型统一获取缓存值
  /// * [key] key
  Future<T?> get<T>(String key) async {
    final SharedPreferences pref = await _prefFuture;
    if (T == String) {
      return pref.getString(key) as T?;
    }

    if (T == bool) {
      return pref.getBool(key) as T?;
    }

    if (T == int) {
      return pref.getInt(key) as T?;
    }

    if (T == double) {
      return pref.getDouble(key) as T?;
    }

    if (T == List) {
      return pref.getStringList(key) as T?;
    }

    return null as T;
  }

  /// 通过泛型统一获取缓存值 - 同步
  ///
  /// 需提前调用`preInit()`
  /// * [key] key
  T? getSync<T>(String key) {
    if (T == String) {
      return _pref.getString(key) as T?;
    }

    if (T == bool) {
      return _pref.getBool(key) as T?;
    }

    if (T == int) {
      return _pref.getInt(key) as T?;
    }

    if (T == double) {
      return _pref.getDouble(key) as T?;
    }

    if (T == List) {
      return _pref.getStringList(key) as T?;
    }

    return null as T;
  }

  /// 通过泛型统一设置缓存值
  /// * [key] key
  /// * [value] value
  Future<bool> set<T>(String key, T value) async {
    final SharedPreferences pref = await _prefFuture;
    if (value is String) {
      return pref.setString(key, value);
    }

    if (value is bool) {
      return pref.setBool(key, value);
    }

    if (value is int) {
      return pref.setInt(key, value);
    }

    if (value is double) {
      return pref.setDouble(key, value);
    }

    if (value is List<String>) {
      return pref.setStringList(key, value);
    }

    return false;
  }

  /// 根据key移除
  /// * [key] key
  Future<bool> remove(String key) async {
    final SharedPreferences pref = await _prefFuture;
    return pref.remove(key);
  }

  /// 清除所有
  Future<bool> clear() async {
    final SharedPreferences pref = await _prefFuture;
    return pref.clear();
  }
}
